import subprocess
import os
import psutil
import time
from collections import deque

def start_program(program_path):
    print(f"启动程序：{program_path}")
    parent_directory = os.path.dirname(os.path.dirname(program_path))  # 获取程序路径的上上级目录
    command = f'start cmd /k "conda activate onsite_mine && cd {parent_directory} && python .\\planner && exit"'
    subprocess.Popen(command, shell=True)

def check_resource_usage():
    # 初始化记录CPU和内存使用率的队列
    cpu_usage_queue = deque(maxlen=10)  # 记录过去2秒的CPU使用率，每次检查间隔为0.2秒，因此最大长度为10
    mem_usage_queue = deque(maxlen=10)  # 记录过去2秒的内存使用率，每次检查间隔为0.2秒，因此最大长度为10

    # 检查资源占用情况
    for _ in range(20):
        cpu_usage_queue.append(psutil.cpu_percent())
        mem_usage_queue.append(psutil.virtual_memory().percent)
        time.sleep(0.1)

    # 计算平均CPU和内存使用率以及最高CPU和内存使用率
    avg_cpu_usage = sum(cpu_usage_queue) / len(cpu_usage_queue)
    max_cpu_usage = max(cpu_usage_queue)
    avg_mem_usage = sum(mem_usage_queue) / len(mem_usage_queue)
    max_mem_usage = max(mem_usage_queue)

    # 如果平均CPU或内存占用率超过80%，或最高CPU或内存占用率超过85%，返回True，否则返回False
    if avg_cpu_usage > 80 or avg_mem_usage > 70 or max_cpu_usage > 85 or max_mem_usage > 75:
        print(f"Ave CPU: {avg_cpu_usage:.1f}%,  Max CPU: {max_cpu_usage:.1f}%,  Ave ROM: {avg_mem_usage:.1f}%,  Max ROM: {max_mem_usage:.1f}%, Resource usage is too high, wait")
        return True
    return False

current_directory = os.getcwd()
project_name = os.path.basename(current_directory)
parent_directory = os.path.dirname(current_directory)
source_folder = os.path.join(current_directory)
source_folder_Scenarios = os.path.join(parent_directory,'B卷','驶入驶出停位')
file_list = os.listdir(source_folder_Scenarios)
json_files = [file for file in file_list if file.endswith('.json')]

# 要启动的程序绝对路径列表
programs_to_start = []
for i in range(len(json_files)):
    directory_name = f"{project_name}_{i}" if i > 0 else project_name
    program_path = os.path.join(parent_directory, directory_name, "planner", "__main__.py")
    programs_to_start.append(program_path)

# 逐个启动程序，并检查资源占用情况
for program_path in programs_to_start:
    start_program(program_path)
    time.sleep(1)
    while check_resource_usage():
        time.sleep(2)  # 如果资源占用过高，等待一段时间后重新检查
